package com.xnyzc.lhy.mis.service.impl.coupon;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.exception.CouponException;
import com.xnyzc.lhy.common.penum.coupon.CouponErrorCode;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.coupon.*;
import com.xnyzc.lhy.mis.feign.didi.ICouponService;
import com.xnyzc.lhy.mis.mapper.coupon.OaSysCouponBatchMapper;
import com.xnyzc.lhy.mis.service.coupon.IOaSysCouponBatchService;
import com.xnyzc.lhy.mis.service.coupon.IOaSysCouponDefService;
import com.xnyzc.lhy.mis.service.coupon.IOaSysCouponGroupService;
import com.xnyzc.lhy.mis.service.coupon.IOaSysCouponInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 优惠券批次 服务实现类
 * </p>
 *
 * @author haoyfa
 * @since 2019-12-16
 */
@Service
public class OaSysCouponBatchServiceImpl extends ServiceImpl<OaSysCouponBatchMapper, OaSysCouponBatch> implements IOaSysCouponBatchService {
    @Autowired
    OaSysCouponBatchMapper oaSysCouponBatchMapper;

    @Autowired
    IOaSysCouponDefService iOaSysCouponDefService;

    @Autowired
    IOaSysCouponInfoService iOaSysCouponInfoService;

    @Autowired
    IOaSysCouponGroupService iOaSysCouponGroupService;

    @Autowired
    ICouponService iCouponService;

    /**
     * 获取优惠券批次列表(根据优惠券定义ID)
     *
     * @return
     */
    @Override
    public List<CouponBatchSearchResult> queryCouponBatchList(String defId) {
        if(StringUtils.isEmpty(defId))
        {
            throw new CouponException(CouponErrorCode.paramError);
        }

        //查询优惠券批次
        QueryWrapper<OaSysCouponBatch> oaSysCouponBatchWrapper = new QueryWrapper<OaSysCouponBatch>();

        //优惠券定义ID
        oaSysCouponBatchWrapper.eq(OaSysCouponBatch.DEF_ID, defId);

        //正常记录 =0
        oaSysCouponBatchWrapper.eq(OaSysCouponBatch.DELETED, 0);

        //查询数据
        List<OaSysCouponBatch> oaSysCouponBatchList = oaSysCouponBatchMapper.selectList(oaSysCouponBatchWrapper);

        return this.createCouponBatchSearchResult(oaSysCouponBatchList);
    }

    /**
     * 新增优惠券批次
     *
     * @return
     */
    @Override
    public void createCouponBatch(CouponBatchParam couponBatchParam) {
        if(couponBatchParam == null
                || StringUtils.isEmpty(couponBatchParam.getDefId())){
            throw new CouponException(CouponErrorCode.paramError);
        }

        //获取优惠券批次数据
        Date createDate = new Date();
        OaSysCouponBatch oaSysCouponBatch = new OaSysCouponBatch();
        //优惠券定义ID
        oaSysCouponBatch.setDefId(Long.parseLong(couponBatchParam.getDefId()));

        //优惠券批次名称
        oaSysCouponBatch.setBatchName(couponBatchParam.getBatchName());
        //优惠券批次编号
        oaSysCouponBatch.setBatchNo(couponBatchParam.getBatchNo());
        //有效期开始
        if(couponBatchParam.getValidityPeriodStart() != null) {
            oaSysCouponBatch.setValidityPeriodStart(LocalDate.parse(couponBatchParam.getValidityPeriodStart()));
        }
        //有效期结束
        if(couponBatchParam.getValidityPeriodEnd() != null) {
            oaSysCouponBatch.setValidityPeriodEnd(LocalDate.parse(couponBatchParam.getValidityPeriodEnd()));
        }
        //有效时间段开始
        if(couponBatchParam.getValidityTimeStart() != null){
            oaSysCouponBatch.setValidityTimeStart(LocalTime.parse(couponBatchParam.getValidityTimeStart()));
        }
        //有效时间段结束
        if(couponBatchParam.getValidityTimeEnd() != null){
            oaSysCouponBatch.setValidityTimeEnd(LocalTime.parse(couponBatchParam.getValidityTimeEnd()));
        }
        //门槛金额
        if(couponBatchParam.getBaseLine() != null){
            oaSysCouponBatch.setBaseLine(new BigDecimal(couponBatchParam.getBaseLine()));
        }
        //折扣上限金额
        if(couponBatchParam.getHighLine() != null){
            oaSysCouponBatch.setHighLine(new BigDecimal(couponBatchParam.getHighLine()));
        }
        //总张数
        if(couponBatchParam.getTotalAmount() != null){
            oaSysCouponBatch.setTotalAmount(Integer.parseInt(couponBatchParam.getTotalAmount()));
        }

        Long defId = IDUtil.nextId();
        oaSysCouponBatch.setId(defId);
        oaSysCouponBatch.setCreateTime(createDate);
        oaSysCouponBatch.setCreateUser(TokenUtil.getTokenUserId());
        oaSysCouponBatch.setDeleted(0);
        oaSysCouponBatch.setVersion(0L);
        oaSysCouponBatch.setUpdateTime(createDate);

        oaSysCouponBatchMapper.insert(oaSysCouponBatch);
    }

    /**
     * 有效优惠券查询
     * @return
     */
    @Override
    public List<CouponEffectiveResult> queryEffectiveCouponList(){
        //查询有效优惠券
        List<OaSysCouponBatch> oaSysCouponBatchList = oaSysCouponBatchMapper.getEffectiveCouponBatchList(DateUtil.getDateDay());
        if(oaSysCouponBatchList != null
                && oaSysCouponBatchList.size() > 0){
            //根据定义ID进行分组
            Map<Long, List<OaSysCouponBatch>> oaSysCouponBatchGroupMap =
                    oaSysCouponBatchList.stream().collect(Collectors.groupingBy(OaSysCouponBatch::getDefId));

            List<CouponEffectiveResult> couponEffectiveResultList = new ArrayList<CouponEffectiveResult>(oaSysCouponBatchGroupMap.size());
            for (Long defId : oaSysCouponBatchGroupMap.keySet()) {
                OaSysCouponDef oaSysCouponDef = iOaSysCouponDefService.queryCouponDef(defId.toString());
                if(oaSysCouponDef != null) {
                    CouponEffectiveResult couponEffectiveResult = new CouponEffectiveResult();
                    couponEffectiveResult.setDefId(oaSysCouponDef.getId().toString());
                    couponEffectiveResult.setDefType(oaSysCouponDef.getDefType());
                    couponEffectiveResult.setDefAmount(oaSysCouponDef.getDefAmount().toString());

                    //批次列表
                    couponEffectiveResult.setBatchList(this.createCouponBatchSearchResult(oaSysCouponBatchGroupMap.get(defId)));

                    couponEffectiveResultList.add(couponEffectiveResult);
                }
            }
            return couponEffectiveResultList;

        }else {
            return null;
        }
    }

    /**
     * 发放优惠券，目前滴滴方只支持金额
     *
     * @return
     */
    @Override
    @Transactional
    public void publishCoupon(Long groupId, CouponPublishParam couponPublishParam) {
        //参数校验
        if(couponPublishParam == null
                || StringUtils.isEmpty(couponPublishParam.getBatchId())
                || StringUtils.isEmpty(couponPublishParam.getPublishAmount())
                || StringUtils.isEmpty(couponPublishParam.getPassengerPhone())){
            throw new CouponException(CouponErrorCode.paramEmptyError);
        }

        OaSysCouponBatch oaSysCouponBatch = oaSysCouponBatchMapper.selectById(couponPublishParam.getBatchId());

        if(oaSysCouponBatch != null
                && oaSysCouponBatch.getDefId() != null
                && oaSysCouponBatch.getTotalAmount() - oaSysCouponBatch.getPublishAmount() - Integer.parseInt(couponPublishParam.getPublishAmount()) >= 0){

            //获取优惠券定义
            OaSysCouponDef oaSysCouponDef = iOaSysCouponDefService.queryCouponDef(oaSysCouponBatch.getDefId().toString());
            if(oaSysCouponDef == null)
            {
                throw new CouponException(CouponErrorCode.noCoupon);
            }

            BindCouponParam bindCouponParam = new BindCouponParam();
            //乘客手机号
            bindCouponParam.setPassenger_phone(couponPublishParam.getPassengerPhone());
            //优惠券金额
            bindCouponParam.setCoupon_amount(oaSysCouponDef.getDefAmount().toString());
            DiDiRv bindResult =  iCouponService.bindByUidBack(bindCouponParam);

            if(bindResult == null
                    || bindResult.getErrno() != 0){
                throw new CouponException(CouponErrorCode.didiServerError);
            }

            //滴滴绑定卷成功后，更新发放数量
            oaSysCouponBatch.setPublishAmount(oaSysCouponBatch.getPublishAmount() + Integer.parseInt(couponPublishParam.getPublishAmount()));
            oaSysCouponBatchMapper.updateById(oaSysCouponBatch);

            //创建优惠券信息
            iOaSysCouponInfoService.createCouponInfo(groupId, couponPublishParam, "1", new Date());
        }
        else {
            throw new CouponException(CouponErrorCode.noCoupon);
        }
    }

    /**
     * 批量发放优惠券，目前滴滴方只支持金额
     *
     * @return
     */
    @Override
    @Transactional
    public void batchPublishCoupon(CouponBatchPublishParam couponBatchPublishParam) {
        if(couponBatchPublishParam != null
                && couponBatchPublishParam.getCouponPublishParamList() != null
                && couponBatchPublishParam.getCouponPublishParamList().size() > 0){
            Long batchId = null;
            Long fileId = null;
            //分组批次ID
            if(StringUtils.isNoneEmpty(couponBatchPublishParam.getBatchId())){
                batchId = Long.parseLong(couponBatchPublishParam.getBatchId());
            }
            //分组文件ID
            if(StringUtils.isNoneEmpty(couponBatchPublishParam.getFileId())){
                fileId = Long.parseLong(couponBatchPublishParam.getFileId());
            }

            //创建优惠券分组
            OaSysCouponGroup oaSysCouponGroup = iOaSysCouponGroupService.createCouponInfo(batchId, fileId);

            for (CouponPublishParam couponPublishParam : couponBatchPublishParam.getCouponPublishParamList()) {
                //发放优惠券
                this.publishCoupon(oaSysCouponGroup.getId(), couponPublishParam);
            }
        }else {
            throw new CouponException(CouponErrorCode.paramEmptyError);
        }
    }

    /**
     * 创建优惠券批次查询
     * @param oaSysCouponBatchList
     * @return
     */
    private List<CouponBatchSearchResult> createCouponBatchSearchResult(List<OaSysCouponBatch> oaSysCouponBatchList) {
        if(oaSysCouponBatchList !=null
                && oaSysCouponBatchList.size() >0){
            List<CouponBatchSearchResult> couponBatchSearchResultList = new ArrayList<CouponBatchSearchResult>(oaSysCouponBatchList.size());
            for (OaSysCouponBatch oaSysCouponBatch : oaSysCouponBatchList) {
                CouponBatchSearchResult couponBatchSearchResult = new CouponBatchSearchResult();

                //ID
                couponBatchSearchResult.setBatchId(oaSysCouponBatch.getId().toString());
                //优惠券批次名称
                couponBatchSearchResult.setBatchName(oaSysCouponBatch.getBatchName());
                //优惠券批次编号
                couponBatchSearchResult.setBatchNo(oaSysCouponBatch.getBatchNo());
                //有效期开始
                if(oaSysCouponBatch.getValidityPeriodStart() != null) {
                    couponBatchSearchResult.setValidityPeriodStart(oaSysCouponBatch.getValidityPeriodStart().toString());
                }
                //有效期结束
                if(oaSysCouponBatch.getValidityPeriodEnd() != null) {
                    couponBatchSearchResult.setValidityPeriodEnd(oaSysCouponBatch.getValidityPeriodEnd().toString());
                }
                //有效时间段开始
                if(oaSysCouponBatch.getValidityTimeStart() != null){
                    couponBatchSearchResult.setValidityTimeStart(oaSysCouponBatch.getValidityTimeStart().toString());
                }
                //有效时间段结束
                if(oaSysCouponBatch.getValidityTimeEnd() != null){
                    couponBatchSearchResult.setValidityTimeEnd(oaSysCouponBatch.getValidityTimeEnd().toString());
                }
                //门槛金额
                if(oaSysCouponBatch.getBaseLine() != null){
                    couponBatchSearchResult.setBaseLine(oaSysCouponBatch.getBaseLine().toString());
                }
                //折扣上限金额
                if(oaSysCouponBatch.getHighLine() != null){
                    couponBatchSearchResult.setHighLine(oaSysCouponBatch.getHighLine().toString());
                }
                //总张数
                if(oaSysCouponBatch.getTotalAmount() != null){
                    couponBatchSearchResult.setTotalAmount(oaSysCouponBatch.getTotalAmount().toString());
                }
                //已发放数量
                if(oaSysCouponBatch.getPublishAmount() != null){
                    couponBatchSearchResult.setPublishAmount(oaSysCouponBatch.getPublishAmount().toString());
                }
                //已核销数量
                if(oaSysCouponBatch.getCheckAmount() != null){
                    couponBatchSearchResult.setCheckAmount(oaSysCouponBatch.getCheckAmount().toString());
                }

                couponBatchSearchResultList.add(couponBatchSearchResult);
            }

            return couponBatchSearchResultList;
        }
        else{
            return null;
        }
    }
}
